package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.Knowledgebasemanagement;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/2/14 13:21
 */
public class KnowledgeBaseDetailFragment extends BaseFragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.KnowledgeBaseDetailFragment.EXTRA_CONTENT";

  private static final int REQUEST_RP1 = 1;
  private static final int REQUEST_RP2 = 2;
  private static final int REQUEST_RP3 = 3;
  private static final int REQUEST_RP4 = 4;
  private final int KNOWLEDGE_TYPE = 5;
  @BindView(R.id.wv_primaryCoverage) WebView wvPrimaryCoverage;

  private String mFilePath1 = "";//文件本地路径
  private String mFilePath2 = "";//文件本地路径
  private String mFilePath3 = "";//文件本地路径
  private String mFilePath4 = "";//文件本地路径

  @BindView(R.id.tv_docKindName) TextView tvDocKindName;
  @BindView(R.id.et_docKeyWords) EditText etDocKeyWords;
  @BindView(R.id.et_title) EditText etTitle;
  @BindView(R.id.et_primaryCoverage) EditText etPrimaryCoverage;
  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;
  @BindView(R.id.tv_checkStaffName) TextView tvCheckStaffName;
  @BindView(R.id.tv_checkDate) TextView tvCheckDate;
  @BindView(R.id.ll_checkInfo) LinearLayout llCheckInfo;
  @BindView(R.id.tv_filePath1) TextView tvFilePath1;
  @BindView(R.id.iv_filePath1) ImageView ivFilePath1;
  @BindView(R.id.tv_filePath2) TextView tvFilePath2;
  @BindView(R.id.iv_filePath2) ImageView ivFilePath2;
  @BindView(R.id.tv_filePath3) TextView tvFilePath3;
  @BindView(R.id.iv_filePath3) ImageView ivFilePath3;
  @BindView(R.id.tv_filePath4) TextView tvFilePath4;
  @BindView(R.id.iv_filePath4) ImageView ivFilePath4;

  private Knowledgebasemanagement mContent;
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private static final int SAVE_SUB_DEL = 0;
  private static final int PASS_BACK_CANCLE = 1;
  private static final int BACK_CANCLE = 2;
  private static final int SAVE = 3;
  private static final int NO = 4;
  private static final int SAVE_SUB = 5;
  private String dataStatus;
  private String docKindCode;
  private String mId;
  private int menuType;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.knowledgebase);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    mContent = (Knowledgebasemanagement) getArguments().getSerializable(EXTRA_CONTENT);
    if (mContent != null) {
      mId = mContent.getId();
      docKindCode = mContent.getDocKindCode();
      mFilePath1 = mContent.getFilepath1();
      mFilePath2 = mContent.getFilepath2();
      mFilePath3 = mContent.getFilepath3();
      mFilePath4 = mContent.getFilepath4();

      dataStatus = mContent.getDataStatus();
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus) || DataStatus.NEWBACK.equalsIgnoreCase(
          dataStatus)) {
        //草稿和终止:  保存和提交,删除
        menuType = SAVE_SUB_DEL;
      }
      if (DataStatus.SUBMIT.equalsIgnoreCase(dataStatus)) {
        //提交状态:  退回、审核通过和作废
        menuType = PASS_BACK_CANCLE;
      }
      if (DataStatus.PUBLIS.equalsIgnoreCase(dataStatus)) {
        //审核通过:  终止、作废
        menuType = BACK_CANCLE;
      }
      if (DataStatus.ORDER_CANCEL.equalsIgnoreCase(dataStatus)) {
        //已作废:  没有菜单
        menuType = NO;
      }
    } else {
      //新增:  保存
      mId = UUID.randomUUID().toString();
      menuType = SAVE;
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_knowledge_base, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  public void bindData() {
    if (mContent == null) {
      //添加界面
      llCheckInfo.setVisibility(View.GONE);
      tvRegStaffName.setText(mUser.getRealName());
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
    } else {
      //详情界面
      tvDocKindName.setText(mContent.getDocKindName());
      etDocKeyWords.setText(mContent.getDocKeyWords());
      etTitle.setText(mContent.getTitle());
      etPrimaryCoverage.setText(Html.fromHtml(mContent.getPrimaryCoverage()));
      //webview

      String content = MyUtils.parseWebImage(mContent.getPrimaryCoverage());//图片自适应
      wvPrimaryCoverage.loadDataWithBaseURL(ApiConst.getUrlMain(), content, "text/html", "utf-8",
          null);//图文混排

      etRemark.setText(mContent.getRemark());
      tvRegStaffName.setText(mContent.getRegStaffName());
      tvRegDate.setText(
          MyDateUtil.parseDateToString(MyDateUtil.stringToDate(mContent.getRegDate())));
      tvCheckStaffName.setText(mContent.getCheckStaffName());
      tvCheckDate.setText(mContent.getCheckDate());
      tvFilePath1.setText(mContent.getFileoriginalname1());
      tvFilePath2.setText(mContent.getFileoriginalname2());
      tvFilePath3.setText(mContent.getFileoriginalname3());
      tvFilePath4.setText(mContent.getFileoriginalname4());

      if (DataStatus.SUBMIT.equalsIgnoreCase(dataStatus) || DataStatus.PUBLIS.equalsIgnoreCase(
          dataStatus) || DataStatus.ORDER_CANCEL.equalsIgnoreCase(dataStatus)) {
        //提交,审核通过和作废 :  不可编辑
        tvDocKindName.setEnabled(false);
        etDocKeyWords.setEnabled(false);
        etTitle.setEnabled(false);
        etPrimaryCoverage.setEnabled(false);
        etRemark.setEnabled(false);
        ivFilePath1.setVisibility(View.GONE);
        ivFilePath2.setVisibility(View.GONE);
        ivFilePath3.setVisibility(View.GONE);
        ivFilePath4.setVisibility(View.GONE);
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //        inflater.inflate(R.menu.menu_know_base, menu);
    //        switch (menuType) {
    //            case SAVE:
    //                menu.getItem(0).setVisible(true);
    //                menu.getItem(1).setVisible(true);
    //                break;
    //            case SAVE_SUB_DEL:
    //                menu.getItem(0).setVisible(true);
    //                menu.getItem(1).setVisible(true);
    //                menu.getItem(2).setVisible(true);
    //                break;
    //            case PASS_BACK_CANCLE:
    //                menu.getItem(3).setVisible(true);
    //                menu.getItem(4).setVisible(true);
    //                menu.getItem(5).setVisible(true);
    //                break;
    //            case BACK_CANCLE:
    //                menu.getItem(4).setVisible(true);
    //                menu.getItem(5).setVisible(true);
    //                break;
    //            case NO:
    //                break;
    //            default:
    //                break;
    //
    //        }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        volleyPostDelete();
        return true;
      case R.id.menu_item_submit:
        //提交:  保存并提交
        //                volleyPostDataStatus(DataStatus.SUBMIT);
        if (isCorrectInput()) {
          volleyPostSave(SAVE_SUB);
        }
        return true;
      case R.id.menu_item_checked:
        //审核通过
        volleyPostDataStatus(DataStatus.PUBLIS);
        return true;
      case R.id.menu_item_newback:
        //终止
        volleyPostDataStatus(DataStatus.NEWBACK);
        return true;
      case R.id.menu_item_cancel:
        //作废
        volleyPostDataStatus(DataStatus.ORDER_CANCEL);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostDataStatus(String dataStatus) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGE_STATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("dataStatus", dataStatus);
    if (DataStatus.NEWBACK.equalsIgnoreCase(dataStatus) || DataStatus.ORDER_CANCEL.equalsIgnoreCase(
        dataStatus)) {
      //退回或作废:  传审核人id和name
      params.put("checkStaffId", mContent.getCheckStaffId());
      params.put("checkStaffName", mContent.getCheckStaffName());
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGE_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  private void volleyPostSave(final int typeCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGE_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("docKindCode", docKindCode);
    params.put("title", etTitle.getText().toString());
    params.put("docKeyWords", etDocKeyWords.getText().toString());
    params.put("filepath1", mFilePath1);
    params.put("filepath2", mFilePath2);
    params.put("filepath3", mFilePath3);
    params.put("filepath4", mFilePath4);
    params.put("primaryCoverage", etPrimaryCoverage.getText().toString());
    params.put("remark", etRemark.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            if (SAVE == typeCode) {
              ToastUtil.show(R.string.success_operation);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
            if (SAVE_SUB == typeCode) {
              volleyPostDataStatus(DataStatus.SUBMIT);
            }
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog;
    FragmentManager fm = getFragmentManager();
    if (KNOWLEDGE_TYPE == requestCode) {
      dialog = PublishKnowledgeTypeDialogFragment.newInstance(
          PublishKnowledgeTypeDialogFragment.KNOWLEDGE_BASE);
    } else {
      dialog = BaseConfirmDialogFragment.newInstance(R.string.uploadHint);
    }
    //        switch (requestCode) {
    //            case KNOWLEDGE_TYPE:
    //                dialog = PublishKnowledgeTypeDialogFragment.newInstance(PublishKnowledgeTypeDialogFragment.KNOWLEDGE_BASE);
    //                break;
    //            case UPLOAD_FILE:
    //                dialog = BaseConfirmDialogFragment.newInstance(R.string.uploadHint);
    //                break;
    //          default:
    //              break;
    //        }
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  public static KnowledgeBaseDetailFragment newInstance(Knowledgebasemanagement content) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    KnowledgeBaseDetailFragment fragment = new KnowledgeBaseDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @OnClick({
      R.id.tv_docKindName, R.id.tv_filePath1, R.id.iv_filePath1, R.id.tv_filePath2,
      R.id.iv_filePath2, R.id.tv_filePath3, R.id.iv_filePath3, R.id.tv_filePath4, R.id.iv_filePath4
  }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_docKindName:
        showDialog(KNOWLEDGE_TYPE);
        break;

      case R.id.tv_filePath1:
        if (mContent != null) {
          downFile(mContent.getFilepath1());
        }

        break;
      case R.id.iv_filePath1:
        chooseFile(REQUEST_RP1);
        break;
      case R.id.tv_filePath2:
        if (mContent != null) {
          downFile(mContent.getFilepath2());
        }
        break;
      case R.id.iv_filePath2:
        chooseFile(REQUEST_RP2);
        break;
      case R.id.tv_filePath3:
        if (mContent != null) {
          downFile(mContent.getFilepath3());
        }
        break;
      case R.id.iv_filePath3:
        chooseFile(REQUEST_RP3);
        break;
      case R.id.tv_filePath4:
        if (mContent != null) {
          downFile(mContent.getFilepath4());
        }
        break;
      case R.id.iv_filePath4:
        chooseFile(REQUEST_RP4);
        break;
    }
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.show(fm, "");
    }
  }

  private boolean isCorrectInput() {
    if (TextUtils.isEmpty(tvDocKindName.getText().toString())) {
      ToastUtil.show("请选择知识库类别");
      return false;
    }
    if (TextUtils.isEmpty(etDocKeyWords.getText().toString())) {
      ToastUtil.show("请填写关键字");
      return false;
    }
    if (TextUtils.isEmpty(etTitle.getText().toString())) {
      ToastUtil.show("请填写标题");
      return false;
    }
    //        if (TextUtils.isEmpty(etPrimaryCoverage.getText().toString())) {
    //            ToastUtil.show("请填写内容简介");
    //            return false;
    //        }
    return true;
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == KNOWLEDGE_TYPE) {
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      docKindCode = dialog.getId();
      tvDocKindName.setText(dialog.getName());
    }
    if (requestCode == REQUEST_RP1) {
      //            showDialog(UPLOAD_FILE1);
      volleyPostExtra(getFile(data), REQUEST_RP1, tvFilePath1);
    }
    if (requestCode == REQUEST_RP2) {
      //            showDialog(UPLOAD_FILE2);
      volleyPostExtra(getFile(data), REQUEST_RP2, tvFilePath2);
    }
    if (requestCode == REQUEST_RP3) {
      //            showDialog(UPLOAD_FILE3);
      volleyPostExtra(getFile(data), REQUEST_RP3, tvFilePath3);
    }
    if (requestCode == REQUEST_RP4) {
      //            showDialog(UPLOAD_FILE4);
      volleyPostExtra(getFile(data), REQUEST_RP4, tvFilePath4);
    }
    //        if (requestCode == UPLOAD_FILE1) {
    //            volleyPostExtra(getFile(data), REQUEST_RP1, tvFilePath1);
    //        }
    //        if (requestCode == UPLOAD_FILE2) {
    //            volleyPostExtra(getFile(data), REQUEST_RP2, tvFilePath2);
    //        }
    //        if (requestCode == UPLOAD_FILE3) {
    //            volleyPostExtra(getFile(data), REQUEST_RP3, tvFilePath3);
    //        }
    //        if (requestCode == UPLOAD_FILE4) {
    //            volleyPostExtra(getFile(data), REQUEST_RP4, tvFilePath4);
    //        }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostExtra(String resourcefilePath, int requestCode, TextView tvFilePath) {

    if (!TextUtils.isEmpty(resourcefilePath)) {
      new FileNetWorkUtil(getActivity()).upLoadFile(resourcefilePath, ApiConst.URL_UPLOAD_FILE,
          "intelligentFarmbyWJ.knowledge_base_management", mId,
          new myUpLoadHandler(requestCode, tvFilePath), false);
    }
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    private TextView mtvFilePath;
    private int requestCode;

    public myUpLoadHandler(int requestCode, TextView tvFilePath) {
      this.requestCode = requestCode;
      this.mtvFilePath = tvFilePath;
    }

    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      ToastUtil.show(R.string.fileUploadFailure);
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          ToastUtil.show(R.string.wrong_data);
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          // 上传成功,再上传数据
          ToastUtil.show(R.string.fileUploadSuccess);
          String selcurFile = result.getMessage();
          mtvFilePath.setText(FileUtil.getFileNameByFilePath(selcurFile));
          switch (requestCode) {
            case REQUEST_RP1:
              mFilePath1 = selcurFile;
              break;
            case REQUEST_RP2:
              mFilePath2 = selcurFile;
              break;
            case REQUEST_RP3:
              mFilePath3 = selcurFile;
              break;
            case REQUEST_RP4:
              mFilePath4 = selcurFile;
              break;
            default:
              break;
          }
          LogUtil.i("selcurFile==" + selcurFile);
        } else {
          MyUtils.dismissDialog();
          ToastUtil.show(result.getMessage());
        }
      } catch (JsonSyntaxException | Resources.NotFoundException e) {
        e.printStackTrace();
        ToastUtil.show(R.string.fileUploadFailure);
      }
    }
  }
}
